package com.sky.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 登录实现类
 *
 * @Author mr.lcc
 * @Data 2025/5/22 19:40
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WechatService wechatService;

    /**
     * 微信登录接口
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 1.实现逻辑，和传统的登录不一致。
        log.info("1.调用微信接口服务，获取微信用户的openid");
        //String openid = getOpenid(userLoginDTO.getCode());
        String openid = wechatService.getOpenId(userLoginDTO.getCode());

        // 2.判断openid是否为空，如果为空表示登录失败，抛出业务异常 非空检查\长度检查 如果是 null，则返回 false
        log.info("2.判断openid是否为空，如果为空表示登录失败，抛出业务异常");
        if (!StringUtils.hasLength(openid)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 3.判断用户是否为新用户
        log.info("3.判断用户是否为新用户");
        User oneUser = this.lambdaQuery().eq(User::getOpenid, openid).one();

        // 4.如果是新用户自动完成注册
        if (ObjectUtils.isEmpty(oneUser)) {
            oneUser = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            log.info("3.1.新用户自动完成注册");
            userMapper.insert(oneUser);
        }

        // 5.返回用户对象
        return oneUser;
    }
}
